package org.wangblue.query;

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.wangblue.common.Client;

/**
 * @Description: 组合查询
 * @Author: WangBlue
 * @Create: 2024-10-24 11:19
 * @Version: 1.0
 **/

public class ComposeQuery {
    private static final String INDEX_NAME = "user";
    public static void main(String[] args) {
        try (RestHighLevelClient client = Client.getClient()) {
            // 1. 创建搜索请求对象
            SearchRequest request = new SearchRequest();
            request.indices(INDEX_NAME);

            // 2. 构建查询的请求体
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            // 3. 必须包含
            boolQueryBuilder.must(QueryBuilders.termQuery("sex", "男"));

            // 4. 不一定包含
            boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "张三"));

            // 5. 可能包含
            boolQueryBuilder.should(QueryBuilders.matchQuery("name", "李四"));
            sourceBuilder.query(boolQueryBuilder);
            request.source(sourceBuilder);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            // 6. 查询匹配
            SearchHits hits = response.getHits();
            System.out.println("took:" + response.getTook());
            System.out.println("timeout:" + response.isTimedOut());
            System.out.println("total:" + hits.getTotalHits());
            System.out.println("MaxScore:" + hits.getMaxScore());
            System.out.println("hits========>>");
            for (SearchHit hit : hits) {
                //输出每条查询的结果信息
                System.out.println(hit.getSourceAsString());
            }
            System.out.println("<<========");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
